<template>
  <div :class="customerClass">
    <Tree ref="tree" :show-checkbox="showCheckBox" :data="areaListFilter" @on-check-change="onCheckChange" />
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getOriginData } from '@/util'
export default {
  props: {
    customerClass: {
      type: String,
      default: ''
    },
    showCheckBox: {
      type: Boolean,
      default: true
    },
    checkedIdList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      currValue: [],
      list: []
    }
  },
  computed: {
    areaListFilter () {
      let val = getOriginData(this.tree)

      const ck = (arr) => {
        arr.forEach(item => {
          if (this.checkedIdList.find(i => i == item.id)) {
            item.checked = true
          } else {
            item.checked = false
          }
          if (item.children && item.children.length) {
            ck(item.children)
          }
        })
      }
      if (this.checkedIdList.length) {
        ck(val)
      }
      return [{ title: '选择业务区域', expand: false, children: val }]
    },
    ...mapGetters(['tree'])
  },
  mounted () {
    if (!this.tree || !this.tree.length) {
      this.$store.dispatch('ajaxAddressTree', this.checkedIdList)
    }
  },
  methods: {
    onCheckChange (value, currentValue) {
      let parent
      let grandfather
      if (currentValue.treeLevel === 1) {
        parent = this.areaListFilter[0]
      } else if (currentValue.treeLevel === 2) {
        for (const item of this.areaListFilter[0].children) {
          if (item.id === currentValue.parentId) {
            parent = item
            grandfather = this.areaListFilter[0]
            break
          }
        }
      } else if (currentValue.treeLevel === 3) {
        for (const item of this.areaListFilter[0].children) {
          for (const child of item.children) {
            if (child.id === currentValue.parentId) {
              parent = child
              grandfather = item
              break
            }
          }
        }
      }
      this.$emit('onCheckChangeArea', value, this.$refs.tree.getCheckedNodes())
      this.$emit('checkChangeArea', { currentValue, parent, grandfather })
    },
    updateArea (arr) {
      this.currValue = arr
    }
  }
}
</script>

